<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Container\ContainerInterface;

abstract class AbstractController
{
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @Inject
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var ResponseInterface
     */
    protected $response;

    /**
     * @param array $data
     * @param string $message
     * @return array
     * 统一接口成功格式
     */
    public function success(array $data = [], string $message = 'success'): array
    {
        return [
            'code' => 200,
            'message' => $message,
            'data' => $data,
            'timestamp' => time()
        ];
    }

    /**
     * @param int $code
     * @param string $message
     * @param array|null $data
     * @return array
     * 统一接口失败格式
     */
    public function fail(int $code = 40002, string $message = '请求失败', array $data = null): array
    {
        return [
            'code' => $code,
            'message' => $message,
            'data' => $data,
            'errors'=> ($data && isset($data['errors'])?$data['errors']:null),
            'timestamp' => time()
        ];
    }

    /**
     *  解析参数
     * @param RequestInterface $request
     * @return mixed
     */
    public function parseParams(RequestInterface $request): mixed
    {
        return json_decode($request->getBody()->getContents(), true);
    }
}
